<template>
  <div class="user-list-container">
    <h1 style="font-size: 20px">用户管理</h1>
    <div class="search-bar">
      <input v-model="searchQuery" placeholder="搜索用户名、邮箱或角色" />
      <button @click="performSearch">搜索</button>
      <button @click="clearSearch">清空搜索</button>
      <button @click="openNewUserModal">新增用户</button> <!-- 新增用户按钮 -->
    </div>
    <table>
      <thead>
      <tr>
        <th>
          <input type="checkbox" v-model="allSelected" @change="toggleSelectAll" style="width: 20px; height: 20px; margin: 0; padding: 0;"/>
        </th>
        <th>用户名</th>
        <th>邮箱</th>
        <th>角色</th>
        <th>创建时间</th>
        <th>年级</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="user in paginatedUsers" :key="user.id">
        <td>
          <input type="checkbox" :value="user.id" v-model="selectedUsers" style="width: 20px; height: 20px; margin: 0; padding: 0;"/>
        </td>
        <td style="font-size: 17px">{{ user.username }}</td>
        <td style="font-size: 17px">{{ user.email }}</td>
        <td style="font-size: 17px">{{ user.role }}</td>
        <td style="font-size: 17px">{{ user.createdAt }}</td>
        <td style="font-size: 17px">{{ user.grade }}</td>
        <td>
          <el-button @click="openEditModal(user)" style="background-color: #409EFF; color: white;">修改</el-button>
          <el-button @click="deleteUser(user.id)" style="background-color: #ff4040; color: white;">删除</el-button> <!-- 删除按钮 -->
        </td>
      </tr>
      </tbody>
    </table>
    <div class="button-container">
      <el-button @click="deleteSelectedUsers" style="background-color: #ff4040; color: white;">批量删除</el-button>
    </div>

    <!-- 分页部分 -->
    <div class="pagination" v-if="totalPages > 1">
      <button @click="changePage(currentPage - 1)" :disabled="currentPage === 1">上一页</button>
      <span>{{ currentPage }} / {{ totalPages }}</span>
      <button @click="changePage(currentPage + 1)" :disabled="currentPage >= totalPages">下一页</button>

      <!-- 输入框和跳转按钮 -->
      <input type="number" v-model="pageInput" min="1" :max="totalPages" />
      <button @click="jumpToPage">跳转</button>
    </div>

    <!-- 用户详情弹窗 -->
<!--    <div v-if="isModalOpen" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeModal">&times;</span>
        <h2>用户详情</h2>
        <p><strong>用户名:</strong> {{ selectedUser.username }}</p>
        <p><strong>用户ID:</strong> {{ selectedUser.id }}</p>
        <p><strong>邮箱:</strong> {{ selectedUser.email }}</p>
        <p><strong>角色:</strong> {{ selectedUser.role }}</p>
        <p><strong>创建时间:</strong> {{ selectedUser.createdAt}}</p>
        <p><strong>年级:</strong> {{ selectedUser.grade }}</p>

        <div class="button-container">
          <el-button @click="copyToClipboard(selectedUser.username)" style="background-color: #409EFF; color: white;">复制用户名</el-button>
          <el-button @click="copyToClipboard(selectedUser.id)" style="background-color: #409EFF; color: white;">复制用户ID</el-button>
          <el-button @click="openEditModal(selectedUser)" style="background-color: #409EFF; color: white;">修改</el-button> &lt;!&ndash; 修改按钮 &ndash;&gt;
        </div>
      </div>
    </div>-->

    <!-- 新增用户弹窗 -->
    <div v-if="isNewUserModalOpen" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeNewUserModal">&times;</span>
        <h2>新增用户</h2>
        <div class="input-group">
          <input v-model="newUser.username" placeholder="用户名" />
        </div>
        <div class="input-group">
          <input type="password" v-model="newUser.password" placeholder="密码" />
        </div>
        <div class="input-group">
          <input v-model="newUser.email" placeholder="邮箱" />
        </div>
        <div class="input-group">
          <label for="role">角色:</label>
          <select v-model="newUser.role" id="role" class="form-control">
            <option value="">请选择角色</option>
            <option value="USER" class="option">USER</option>
            <option value="ADMIN" class="option">ADMIN</option>
          </select>
        </div>
        <div class="input-group">
          <label for="role">角色:</label>
          <select v-model="newUser.grade" id="grade" class="form-control">
            <option value="">请选择年级</option>
            <option value="2020级" class="option">2020级</option>
            <option value="2021级" class="option">2021级</option>
            <option value="2022级" class="option">2022级</option>
            <option value="2023级" class="option">2023级</option>
            <option value="2024级" class="option">2024级</option>
            <option value="2025级" class="option">2025级</option>
            <option value="2026级" class="option">2026级</option>
            <option value="2027级" class="option">2027级</option>
            <option value="2028级" class="option">2028级</option>
            <option value="2029级" class="option">2029级</option>
            <option value="2030级" class="option">2030级</option>
          </select>
        </div>
        <div class="button-container">
          <el-button @click="addNewUser" style="background-color: #409EFF; color: white;">提交</el-button>
        </div>
      </div>
    </div>

    <!-- 修改用户弹窗 -->
    <div v-if="isEditModalOpen" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeEditModal">&times;</span>
        <h2>修改用户</h2>
        <div class="input-group">
          <input v-model="editedUser.username" placeholder="用户名" />
        </div>
        <div class="input-group">
          <input type="password" v-model="editedUser.password" placeholder="密码" />
        </div>
        <div class="input-group">
          <input v-model="editedUser.email" placeholder="邮箱" />
        </div>
        <div class="input-group">
          <input v-model="editedUser.role" placeholder="角色" />
        </div>
        <div class="input-group">
          <input v-model="editedUser.grade" placeholder="年级" />
        </div>
        <div class="button-container">
          <el-button @click="updateUser" style="background-color: #409EFF; color: white;">更新</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      users: [],
      filteredUsers: [],
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      pageInput: 1, // 新增页码输入
      isModalOpen: false,
      isNewUserModalOpen: false, // 新增用户模态框状态
      isEditModalOpen: false, // 修改用户模态框状态
      allSelected: false, // 跟踪是否全选
      selectedUsers: [], // 存储选中的用户 ID
      selectedUser: {},
      newUser: { // 新增用户的数据模型
        username: '',
        password: '',
        email: '',
        role: '',
        grade: '',
        createdAt:''
      },
      editedUser: {
        username: '',
        password: '',
        email: '',
        role: '',
        grade: ''
      } // 修改用户的数据模型
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.filteredUsers.length / this.pageSize);
    },
    paginatedUsers() {
      const start = (this.currentPage - 1) * this.pageSize;
      return this.filteredUsers.slice(start, start + this.pageSize);
    },
    allSelected: {
      get() {
        return this.selectedUsers.length === this.paginatedUsers.length;
      },
      set(value) {
        if (value) {
          this.selectedUsers = this.paginatedUsers.map(user => user.id);
        } else {
          this.selectedUsers = [];
        }
      }
    }
  },

  methods: {
    fetchUsers() {
      axios.get('http://localhost:8080/users/all')
          .then(response => {
            this.users = response.data;
            this.filteredUsers = this.users; // 初始化过滤后的用户
          })
          .catch(error => {
            console.error('Error fetching users:', error);
          });
    },
    performSearch() {
      axios.get('http://localhost:8080/users/search', {
        params: {
          query: this.searchQuery
        }
      })
          .then(response => {
            this.filteredUsers = response.data; // 更新过滤后的用户
            this.currentPage = 1; // 重置当前页为1
            this.pageInput = 1; // 重置输入页码
          })
          .catch(error => {
            console.error('Error searching users:', error);
          });
    },
    clearSearch() {
      this.searchQuery = ''; // 清空搜索框
      this.filteredUsers = this.users; // 重置为所有用户
      this.currentPage = 1; // 重置当前页为1
      this.pageInput = 1; // 重置输入页码
    },
    changePage(page) {
      if (page > 0 && page <= this.totalPages) {
        this.currentPage = page;
        this.pageInput = page; // 更新输入框的页码
      }
    },
    jumpToPage() {
      const page = parseInt(this.pageInput);
      if (page > 0 && page <= this.totalPages) {
        this.changePage(page); // 调用现有的 changePage 方法
      } else {
        alert(`请输入有效的页码（1 到 ${this.totalPages}）`);
      }
    },
    viewDetails(user) {
      this.selectedUser = user;
      this.isModalOpen = true;
    },
    closeModal() {
      this.isModalOpen = false;
    },
    openNewUserModal() {
      this.isNewUserModalOpen = true;
      // 重置新增用户的数据模型
      this.newUser = {
        username: '',
        password: '',
        email: '',
        role: '',
        grade: '',
        createdAt:'',
      };
    },
    closeNewUserModal() {
      this.isNewUserModalOpen = false;
    },
    addNewUser() {
      this.newUser.createdAt = new Date(); // 设置当前时间
      axios.post('http://localhost:8080/users/add', this.newUser)
          .then(response => {
            alert(response.data); // 显示成功消息
            this.fetchUsers(); // 刷新用户列表
            this.closeNewUserModal(); // 关闭模态框
          })
          .catch(error => {
            console.error('Error adding new user:', error);
            alert('新增用户失败');
          });
    },
    deleteUser(id) {
      if (confirm('确定要删除这个用户吗？')) {
        axios.delete(`http://localhost:8080/users/delete/${id}`)
            .then(response => {
              alert(response.data); // 显示成功消息
              this.fetchUsers(); // 刷新用户列表
            })
            .catch(error => {
              console.error('Error deleting user:', error);
              alert('删除用户失败');
            });
      }
    },
    openEditModal(user) {
      this.editedUser = { ...user }; // 复制用户信息到编辑模型
      this.isEditModalOpen = true;
    },
    closeEditModal() {
      this.isEditModalOpen = false;
    },
    updateUser() {
      console.log('Updating user with ID:', this.editedUser.id); // 输出 ID
      console.log('Updating user data:', this.editedUser); // 打印要更新的数据
      axios.put(`http://localhost:8080/users/update/${this.editedUser.id}`,  this.editedUser)
          .then(response => {
            alert(response.data); // 显示成功消息
            this.fetchUsers(); // 刷新用户列表
            this.closeEditModal(); // 关闭模态框
          })
          .catch(error => {
            console.error('Error updating user:', error);
            alert('更新用户失败: ' + error.response.data); // 显示错误信息
          });
    },
    toggleSelectAll() {
      if (this.allSelected) {
        this.selectedUsers = []; // 清空选中的用户
      } else {
        this.selectedUsers = this.paginatedUsers.map(user => user.id); // 选中所有用户
      }
      this.allSelected = !this.allSelected; // 切换全选状态
    },
    deleteSelectedUsers() {
      if (this.selectedUsers.length === 0) {
        alert('请选择要删除的用户');
        return;
      }
      if (confirm('确定要删除这些用户吗？')) {
        const userIds = this.selectedUsers.slice(); // 创建选中用户ID的副本
        this.selectedUsers.forEach(async (id) => {
          try {
            await axios.delete(`http://localhost:8080/users/delete/${id}`);
          } catch (error) {
            console.error('Error deleting user:', error);
            alert('删除用户失败');
            return; // 如果任何一个用户删除失败，则停止删除操作
          }
        });
        alert('所有选中用户删除成功'); // 显示批量删除成功消息
        this.fetchUsers(); // 刷新用户列表
        this.selectedUsers = []; // 清空选中的用户
      }
    },
    copyToClipboard(text) {
      navigator.clipboard.writeText(text)
          .then(() => {
            alert('已复制: ' + text);
          })
          .catch(err => {
            console.error('复制失败:', err);
          });
    }},
  mounted() {
    this.fetchUsers(); // 初始加载所有用户
  }
};
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  text-align: center; /* 居中对齐 */
}

.search-bar input {
  padding: 10px; /* 增加内边距 */
  font-size: 16px; /* 增加字体大小 */
  width: 250px; /* 设置宽度 */
  margin-right: 10px; /* 增加右侧间距 */
}

.search-bar button {
  padding: 10px 15px; /* 增加按钮的内边距 */
  font-size: 16px; /* 增加按钮的字体大小 */
}

table {
  width: 100%;
  border-collapse: collapse;
}

table th, table td {
  border: 1px solid #ddd;
  padding: 8px;
}

.pagination {
  margin-top: 20px;
  text-align: center; /* 居中对齐 */
  font-size: 16px; /* 增大字体大小 */
}

.pagination button {
  margin: 0 10px; /* 增加按钮之间的间隔 */
  padding: 10px 15px; /* 增加按钮的内边距 */
  font-size: 16px; /* 增加按钮的字体大小 */
}

.pagination input {
  width: 60px; /* 设置输入框的宽度 */
  padding: 5px; /* 增加内边距 */
  font-size: 16px; /* 增加输入框的字体大小 */
}

/* 弹窗样式 */
.modal {
  display: flex;
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 90%; /* 调整弹窗的宽度为 90% */
  max-width: 800px; /* 设置弹窗的最大宽度 */
  position: relative;
}

.input-group {
  margin-bottom: 15px; /* 输入框之间的间距 */
}

.form-control{
  width: calc(100% - 20px); /* 输入框宽度为100%减去左右各10px的内边距 */
  padding: 10px; /* 增加内边距 */
  font-size: 16px; /* 增加字体大小 */
  border: 1px solid #ccc; /* 边框样式 */
  border-radius: 4px; /* 圆角样式 */
  resize: vertical; /* 允许垂直调整大小 */
}

.input-group input,
.input-group textarea {
  width: calc(100% - 20px); /* 输入框宽度为100%减去左右各10px的内边距 */
  padding: 10px; /* 增加内边距 */
  font-size: 16px; /* 增加字体大小 */
  border: 1px solid #ccc; /* 边框样式 */
  border-radius: 4px; /* 圆角样式 */
}

.input-group textarea {
  resize: vertical; /* 允许垂直调整大小 */
}

.button-container {
  display: flex;
  justify-content: center; /* 居中对齐 */
  margin-top: 20px; /* 可以根据需要调整顶部间距 */
}

.button-container el-button {
  margin: 0 15px; /* 按钮之间的间隔，左右各15px，总共30px */
}

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
</style>